package com.gdcp.config.aspect;

import com.gdcp.beans.Category;
import com.gdcp.config.annotation.CategoryByAll;
import com.gdcp.service.CategoryService;
import com.gdcp.util.AspectUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.List;

@Slf4j
@Aspect
@Component
public class CategoryByAllAspect {

    @Autowired
    CategoryService categoryService;

    @Pointcut(value = "@annotation(com.gdcp.config.annotation.CategoryByAll)")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void deoBefore(JoinPoint point) throws NoSuchMethodException {
        Method currentMethod = AspectUtil.INSTANCE.getMethod(point);
        //获取操作名称
        CategoryByAll categoryByAll = currentMethod.getAnnotation(CategoryByAll.class);
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

        HttpSession session=attr.getRequest().getSession(true);
        boolean flush = categoryByAll.flush();
        if (flush) {
            //if (session.getAttribute("categoryByAll") == null) {
                List<Category> category = categoryService.queryByAll();
                session.setAttribute("categoryByAll", category);
            //}
        }
    }
}